package com.gqyin.demo.config;

import com.gqyin.demo.domain.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.MongoTransactionManager;
import org.springframework.data.mongodb.config.EnableMongoAuditing;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.List;

/**
 * @author guiqing.yin
 * 2024-04-07 16:08
 */
@Slf4j
@EnableTransactionManagement
@EnableMongoAuditing
@Configuration
public class MongodbConfig {
    private final MongoTemplate mongoTemplate;

    @Autowired
    public MongodbConfig(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    @EventListener(ApplicationReadyEvent.class)
    public void initCollections() {
        List<Class<?>> collections = List.of(User.class);
        collections.forEach(collection -> {
            if (!mongoTemplate.collectionExists(collection)) {
                log.info("Create collection for class: {}", collection.getSimpleName());
                mongoTemplate.createCollection(collection);
            } else {
                String collectionName = mongoTemplate.getCollectionName(collection);
                log.info("Collection {} already exists.", collectionName);
            }
        });
    }

    @Bean
    public MongoTransactionManager transactionManager(MongoDatabaseFactory factory) {
        return new MongoTransactionManager(factory);
    }
}
